<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>批量导入图片</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="format-detection" content="telephone=no">
		<!-- jQuery-->
		<script type="text/javascript" src="/static/plugins/jquery/jquery-3.6.0.min.js"></script>

		<!-- layui-->
		<link rel="stylesheet" href="/static/plugins/layui/2.7.6/css/layui.css" media="all">
		<script src="/static/plugins/layui/2.7.6/layui.js" charset="utf-8"></script>

		<!-- common -->
		<link rel="stylesheet" href="/static/admin/css/common.css" media="all" />
		<link rel="stylesheet" href="/static/admin/css/mini-ease.css" media="all" />
		
		
	</head>

	
	<body>

	<!-- 列表 -->
	<div class="layui-row layui-col-space5" style="width:90%;margin: 0 auto;">

		<div class="layui-col-md12" id="id_panel_left_grid">
			<div class="layui-panel" style="overflow: auto; padding-top: 0.2rem;">
				<div class="mid-content">

					<table class="layui-hide" id="main_table" lay-filter="main_table"></table>

					<script type="text/html" id="toolbarDemo">
						<div class="layui-row" style="height: 40px;" id="toolbarDemoBtn">
							<div class="layui-col-xs12">


								<button type="button" class="layui-btn layui-bg-blue layui-btn-sm" style="margin-left: 0;" lay-on="add-data" id="addBtn">
									<i class="layui-icon layui-icon-add-1 layui-font-12"></i> 导入
								</button>
                                <button type="button" class="layui-btn layui-bg-blue layui-btn-sm" style="margin-left: 0;" lay-event="edit-data"  lay-on="edit-data" id="editCodeBtn">
                                    <i class="layui-icon layui-icon-edit layui-font-12"></i> 批量编辑商品编码
                                </button>

								<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 0;"  lay-on="save-data">
									<i class="layui-icon layui-icon-ok-circle layui-font-12"></i> 保存
								</button>

                                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" style="margin-left: 0;" lay-event="del-data" lay-on="del-data">
                                    <i class="layui-icon layui-icon-delete layui-font-12"></i> 删除
                                </button>
							</div>

						</div>
					</script>
					<script type="text/html" id="templet_index_no">{{d.LAY_TABLE_INDEX+1}}</script>
				</div>
			</div>
		</div>
	</div>


      <script>

		  var newId = 0;//新增数据临时Id
		  var dataList = [];

		  layui.config({
				//自定义layui组件的目录,设定扩展的layui模块的所在目录，一般用于外部模块扩展
				base: '/static/js/layui_extends/'
			}).use(['form', 'element', 'table', 'dropdown', 'util', 'laydate', 'upload', 'YsModal'], function(){
					  var element = layui.element;
					  var table = layui.table;
					  var dropdown = layui.dropdown;
					  var form = layui.form;
					  var util = layui.util;
					  var $ = layui.jquery;
					  var laydate = layui.laydate;
					  var upload = layui.upload;

			  		  var cols =[ //表头
						  [
							  {title: '', type: 'checkbox',  unresize: true, width: '40'},
							  {title: '序号',   align:"center",type:"numbers"},
                              {title: '商品编码', width: '100' , field:'code', align:"center",sort:true},
							  {title: '文件名称', width: '200' , field:'fileName', align:"center",sort:true},
							  {title: '文件大小', width: '100' , field:'fileSize', align:"center",sort:true},
							  {title: '单位', width: '100' , field:'fileSizeUnit', align:"center",sort:true},
							  {title: '文件类型', width: '100' , field:'fileType', align:"center",sort:true},
                              {title: '预览', width: '150' , field:'filePath', align:"center",
                                  templet: function(d){
                                      return `<img src="`+d.filePath+`" data-type="1" height="30" class="preview-all" onclick="layer.photos({photos: {'title': '预览','start': 0,'data': [{'src': '`+d.filePath+`'}]},closeBtn: 1});"/>`;
                                  }
                              },

						  ]
					  ];
					  // 创建渲染实例
					  table.render({
						  id:'main_table'
						  ,elem: '#main_table'
						  ,data:dataList
						  ,toolbar: '#toolbarDemo'
						  ,defaultToolbar: [ 'filter',{
							  title: '刷新页面'
							  ,layEvent: 'LAYTABLE_REFRESH'
							  ,icon: 'layui-icon-refresh'
						  }]
						  ,height: window.innerHeight - 70 // 最大高度减去其他容器已占有的高度差
						  ,where: {}
						  ,cellMinWidth: 95
						  ,limit : 200
						  ,limits : [20,50,200,500]
						  ,page: true
						  ,request: {
							  pageName: 'page',
							  limitName: 'size'
						  }
						  //,skin: 'row'
						  ,even: false // 开启隔行背景
						  ,skin: 'grid'//设置表格边框风格
						  ,cols:cols
						  ,done: function(res){
							  setUpload();
						  }
						  ,error: function(res, msg){
							  console.log(res, msg)
						  }
					  });


					  // 工具栏事件
					  table.on('toolbar(main_table)', function(obj){
						  var id = obj.config.id;
						  var checkStatus = table.checkStatus(id);
                          var datas = checkStatus.data;
						  var othis = lay(this);
						  switch(obj.event){
                              case 'LAYTABLE_REFRESH':
							  {
								  layer.confirm("确定刷新吗？",{
									  btn: ['确定', '取消']
								  }, function (index) {
									  location.reload();
									  layer.close(index);
								  });
								  break;
							  }
                              case 'del-data'://删除
                              {
                                  if(datas.length == 0) {
                                      layer.alert('尚未选中数据');
                                  }else {
                                      for(var j=0;j<datas.length;j++){
                                          var dataListNew = [];
                                          for(var i=0;i<dataList.length;i++){
                                              if(dataList[i].id!=datas[j].id){
                                                  dataListNew.push(dataList[i]);
                                              }
                                          }
                                          dataList = dataListNew;
                                      }
                                      //刷新表单
                                      layui.table.reloadData('main_table', { data: dataList});
                                  }
								  break;
                              }

                              case 'edit-data'://批量修改商品编码
                              {
                                  if(datas.length == 0) {
                                      layer.alert('尚未选中数据');
                                  }else {
                                      chooseModel(datas);
                                  }
								  break;
                              }
						  };
					  });

					  // 普通事件
					  util.on('lay-on', {
						  //保存
						  "save-data": function(){
							  toAdd();
						  },
                          /*
                          "edit-data": function(){
                              toAdd();
                          },

                           */


					  })

				  });



          //弹出层
          function chooseModel(datas) {
              // 打开单选框
              layui.YsModal.init({modalKey: 'TOS_ProductBasis', colCode: 'aaa', parentObj: window,extraData:datas})
          }
          //弹出层回调
          function matchValuesAfterModalSelectRadio(colCode, data,extraData) {
              if (data == "none" || !data) {//没有选中时
                  layer.msg("请选择！", {icon: 7});
              } else {
                  var dataListNew = [];
                  for(var i=0;i<dataList.length;i++){
                      for(var j=0;j<extraData.length;j++) {
                          if(dataList[i].id==extraData[j].id){
                              dataList[i].code =data.code;
                          }
                      }
                      dataListNew.push(dataList[i]);
                  }
                  dataList = dataListNew;
                  //刷新表单
                  layui.table.reloadData('main_table', { data: dataList});
              }
          }


			//上传文件控件初始化
		  function setUpload() {
			  layui.upload.render({
				  //elem: '#upload_files_'+id,
				  //elem: '.upload_files',
				  elem:'#addBtn',
				  url: 'https://file.mini-ease.com/api/outer/upload/uploadForERP_1_0',
				  multiple: true,//多附件上传
				  accept: 'images',
				  auto:true,
				  done: function(res){
					  //var item = this.item;
					  //var id = item[0].id;
					  console.log("上传返回res",res);
					  /*
					  var dataListNew = [];
					  for(var i=0;i<dataList.length;i++){
						  if(dataList[i].id==id){
							  dataList[i].id = newId;
							  dataList[i].fileName = res.data.fileName;
							  dataList[i].filePath = res.data.filePath;
							  dataList[i].fileSize = res.data.fileSize;
							  dataList[i].fileSizeUnit = res.data.fileSizeUnit;
							  dataList[i].fileType = res.data.fileType;
						  }
						  newId--;
						  dataListNew.push(dataList[i]);
					  }
					  dataList = dataListNew;
					   */
					  var code = '';
                      var isCode = res.data.fileName.substring(0, 4);
                      if(isCode == 'HWSP'){
                          code = res.data.fileName.substring(0, 9);
                      }
					  newId++;
					  dataList.push({
						  id:newId,
						  fileName:res.data.fileName,
						  filePath:res.data.filePath,
						  fileSize:res.data.fileSize,
						  fileSizeUnit:res.data.fileSizeUnit,
						  fileType:res.data.fileType,
                          code:code
					  });
					  //console.log('dataList',dataList);
					  //刷新列表
					  layui.table.reloadData('main_table', { data: dataList});
				  },
			  });
		  }


		  //转时间格式
		  function setTimeStr(timestamp) {
			  var date = new Date(timestamp);
			  var year = date.getFullYear();
			  var month = ('0' + (date.getMonth() + 1)).slice(-2);
			  var day = ('0' + date.getDate()).slice(-2);
			  var hours = ('0' + date.getHours()).slice(-2);
			  var minutes = ('0' + date.getMinutes()).slice(-2);
			  var seconds = ('0' + date.getSeconds()).slice(-2);
			  var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
			  return formattedDate;
		  }


		  //新增保存
		  function toAdd() {
		  		if(dataList==null || dataList.length<=0){
					layer.msg('请导入图片！', {icon: 0});
					return ;
				}
			  var errorMsg = null;
			  for(var i=0;i<dataList.length;i++){
				  if(dataList[i].fileName ==undefined || dataList[i].fileName ==null || dataList[i].fileName =='' ){
					  errorMsg = '第'+(i+1)+'行数据，文件为空！';
				  }
				  if(dataList[i].code ==undefined || dataList[i].code ==null || dataList[i].code =='' ){
					  errorMsg = '第'+(i+1)+'行数据，商品编码为空！';
				  }
			  }
			  if(errorMsg!=null){
				  layer.msg(errorMsg, {icon: 0});
				  return ;
			  }
			  var layindex= layer.load(2);
			  $.ajax({
				  url: '/api/inter/tosProductActive/saveImgByBatch',
				  data: {
					  'dataList': JSON.stringify(dataList) //参数list
				  },
				  type: 'POST',
				  async: true,
				  success: function (result) {
					  layer.close(layindex);
					  console.log('保存返回result:',result);
					  if(result.code=='0'){
						  layer.msg("操作成功", {icon: 1});
						  //关闭页面
						  setTimeout(function(){
							  parent.window.layer.closeAll();
							  parent.window.location.reload();
						  }, 3000);

					  } else if (result.code == 1) {//失败
						  layer.msg(result.msg, {icon: 2});
					  }else{//失败
						  layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
					  }
				  },
				  error: function () {
					  layer.close(layindex);
					  layer.msg('不好意思，系统出现问题了，请稍后重试！', {icon: 2});
				  }
			  });
		  }



      </script>

  </body>
</html>